from open_operation import OpenOperation
from student import Student


class DataBase:
    student_list = []

    @staticmethod
    def init():
        with OpenOperation('student.txt', 'r') as f:
            for line in f.readlines():
                if line == '':
                    return
                tmp = line.split(',')
                student = Student(tmp[0], tmp[1], tmp[2], tmp[3], tmp[4])
                DataBase.student_list.append(student)

    @staticmethod
    def add_student_info(student):
        for item in DataBase.student_list:
            if item.stuid == student.stuid:
                print('''
=============================
          添加失败
        该学号已存在
============================
                ''')
                return

        with OpenOperation('student.txt', 'a') as f:
            f.write("{},{},{},{},{}\r".format(
                student.stuid,
                student.name,
                student.english_grade,
                student.python_grade,
                student.java_grade))
        DataBase.student_list.append(student)

    @staticmethod
    def save_student_list():
        with OpenOperation('student.txt', 'w') as f:
            for item in DataBase.student_list:
                f.write("{},{},{},{},{}\r".format(
                    item.stuid,
                    item.name,
                    item.english_grade,
                    item.python_grade,
                    item.java_grade))

    @staticmethod
    def delete_student_info_by_stuid(stuid):
        for item in DataBase.student_list:
            if item.stuid == stuid:
                DataBase.student_list.remove(item)
                DataBase.save_student_list()
                print("删除成功")
                return

    @staticmethod
    def edit_student_info(student):
        for item in DataBase.student_list:
            if item.stuid == student.stuid:
                item = student
                DataBase.save_student_list()
                print("修改成功")
                return

    @staticmethod
    def query_student_info_by_stuid(stuid):
        query_result = []
        for item in DataBase.student_list:
            if item.stuid == stuid:
                query_result.append(item)
        return query_result

    @staticmethod
    def query_student_info_by_name(name):
        query_result = []
        for item in DataBase.student_list:
            if item.name == name:
                query_result.append(item)
        return query_result

    @staticmethod
    def get_student_list():
        return DataBase.student_list
